const { app, BrowserWindow,ipcMain} = require('electron')
const electron = require('electron')
const path = require('path')
const { SerialPort } = require('serialport')
const {ReadlineParser} = require('@serialport/parser-readline')
const dgram = require('dgram');
const client = dgram.createSocket('udp4');
const udp_server = dgram.createSocket('udp4');
const {dialog} = require('electron');
var fs = require("fs");

app.commandLine.appendSwitch('touch-events','enabled');  //app是我的electron创建的实例对象名
var moment = require('moment');
 moment.locale('zh-cn');
 
 

 
let flage=true;
var iptxt="127.0.0.1";
var dataflag =0;
var serialflage=0;

//中英文显示的标志位
var showText ="Eng";
var textFlage="Eng";


udp_server.bind(8000);
var showwin="open";
 //从李明月接受的数据
 var strmsg="";
 //发送给李明月数据
 var messageAll = {"Time":"1999", "D":"FU,0","LC":"99","RC":"99","TUG":"*,*,*,*,*","AC":"P,NO,S,NO","SS":"","DL":"0,0","ES":"0,0","LINE":"","CT":"B,4,S,4"}; 
 let newWindow0;
 let newWindow1;
 let newWindow2;
 let newWindow3;
 let newWindow4;
 let newWindow5;
 let newWindow6;
 let newWindow7;
let newWindow8;
var tempwindow =[newWindow0, newWindow1, newWindow2,newWindow3,newWindow4,newWindow5,newWindow6,newWindow7,newWindow8]

var showindexornot=false;
var port;

function createWindow () {
 	   var displays = screenSort();
	 
	  
	   var path="initpage.html";
	   for(var j=0;j<displays.length;j++){
		if((displays[j].workArea.width) > 1300){
		   	showindexornot=true;
		   }
	   }
	  for( var i = 0; i< displays.length; i++)
	  {
		
		if(showindexornot==true){
			//有抬头显示，走这个
			 path="index"+i+".html"
			tempwindow[i] = new BrowserWindow({
							 fullscreen:true,
							 frame: true,	
							  x: displays[i].bounds.x,
							  y: displays[i].bounds.y, 
							  webPreferences:{
							  nodeIntegration: true,
							 contextIsolation: false,
							  enableRemoteModule:true
							     }
							})
			
			tempwindow[i].loadFile(path);
		}
		else{
			//没有抬头显示，走这个
			var j=i+1;
			 path="index"+j+".html"
			tempwindow[j] = new BrowserWindow({
							 fullscreen:true,
							 frame: false,	
							  x: displays[i].bounds.x,
							  y: displays[i].bounds.y, 
							  webPreferences:{
							  nodeIntegration: true,
							 contextIsolation: false,
							  enableRemoteModule:true
							     }
							})
			require("@electron/remote/main").enable(tempwindow[i].webContents);
			tempwindow[j].loadFile(path);
		}

	  }
       
		createSerialPort(); 
 
}


app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

function sendWindowMessage(targetWindow, message, payload) {
  if (typeof targetWindow === 'undefined') {
    console.log('Target window does not exist')
    return;
  }
  
  if(targetWindow.isDestroyed()){
	  console.log('Target window does not exist')
	  return;
  }
  targetWindow.webContents.send(message, payload)
}

 
   
var threeshow='0';
function createSerialPort(){
  //开启串口，并发送到渲染线程中
  
  SerialPort.list().then(ports => {
		 ports.forEach(port => {
		 
   port = new SerialPort({
	path:  port.path,
	baudRate: 115200,
	autoOpen: false,
  })
  
  port.open(err => {
			   console.log('IsOpen: ', port.isOpen);
			   console.log('Err: ', err);
			   if (err) {
			   }
		   });
  
	port.close(error => {
	serialflage=0;
	   console.log('close: ');
	})  
  const parser = port.pipe(new ReadlineParser({ delimiter: '\r\n' }))
  parser.on('data',function(data){
	
	let strData = data;
		if(typeof(strData) == "undefined") {
			console.log("11111");
			return;
		}
		if((strData.substr(0, 1) != '{')&&(strData.substr(-1) != '}') ) {

			return;
		}
		serialflage=1;
		//舵轮发送
	   try{tempwindow[1].webContents.send("marh-data",JSON.parse(strData)); }
	   catch{}
	  //主机发送
	   try{ tempwindow[2].webContents.send("marh-data",JSON.parse(strData));}
	   catch{}
	  //侧推发送
	   try{tempwindow[8].webContents.send("marh-data",JSON.parse(strData)); }
	  catch{}
	  //三面舵发送 
	  port.write(threeshow, function () {}); 
	  });
	});
  })

}

var today = {};
function udpclient(){

	client.on('close',()=>{
	    console.log('socket已关闭');
	});
	client.on('error',(err)=>{
	    console.log(err);
	});
//var dataaa="127.0.0.1";

	setInterval(function(){	
		
		var _today = moment();		
		  today.date = _today.format('HH:mm:ss'); /*现在的时间*/
		  messageAll.Time=today.date;
		client.send(JSON.stringify(messageAll),"8888",iptxt);
		
	},500);
}

function udpserver(){
	
	udp_server.on('message', function (msg, rinfo) {
    strmsg = msg.toString();
		dataflag=dataflag+1;
		try{
			var nstatus=JSON.parse(strmsg);
			threeshow=nstatus.RUD;
			showalldata(strmsg,"data");
		}
		catch{

		}
	});
}


//做一个定时器   检测李明月的数据，如果没有，则
var t2= setInterval(function(){	

		if(dataflag < 10){
			threeshow="0";
			var tempdata = {"WD":"0.00","WS":"0.00","WH":"100","RPM":"0","SPD":"0.00","XSPD":"0.00","ROT":"0.00","CRS":"0.00","RUD":"0.00","HEAD":"0.00","MAG":"0.00","D":"0.50,0.50,5.00,20.00,10.00,0.00,1000.00,1000.00","Tug":"99,0","AC":" P,0.00,0.00, 0.00, 0.00,S ,0.00,0.00, 0.00, 0.00","DL":"2,0.00,0,0.00,2,0.00,0.00","ES":"0.00,0.00","LC":"0.00,0.00,0.00,0.00","LINE":"99,0.0,0.0","LG":"0","SF":"FALSE","RF":"FALSE","WDF":"FALSE","SSF":"FALSE","RAF":"FALSE","RPMF":"FALSE","APF":"FALSE","MEF":"FALSE","RC":"0.00,0.00,0.00,0.00","LRPM":"0","CT":"100"};
			tempdata = JSON.stringify(tempdata);
			showalldata(tempdata,"data");
		}
		dataflag=0;
		

 },25000);	

//做一个定时器   检测串口的数据，如果没有，则	
  var t1= setInterval(function(){	
if(serialflage==1){
	//正常
	console.log("serial true");
}
	else{
			createSerialPort();
			try{tempwindow[1].webContents.send("marh-data",{"D":"1000"}); }
			catch{}
		}
		
	serialflage=0;	
		

 },5000);

	
	

//先加载倒计时界面
//做个定时器，监视倒计时界面
//清除定时器，加载程序
//倒计时界面
app.whenReady().then(() => {
	//接受所有页面的消息
	  ipcMain.on('megfromwhere', (event, message) => {
	       dealdata(message);
		 //需要改一下 每一个子线程更新自己的数据；
	  })
	//屏幕排序，逐个显示
	var displays = screenSort();
	for(var i = 0;i < displays.length;i++)
	{
	
		tempwindow[i] = new BrowserWindow({
		    　　fullscreen:true,
				frame: false,
		   　　 x: displays[i].bounds.x,
		    　　y: displays[i].bounds.y,
			 webPreferences:{
			         nodeIntegration: true,
			         contextIsolation: false,
					 enableRemoteModule: true
			     }
		　　})
			tempwindow[i].loadFile('initpage.html');
		} 
 });

//2定时器

var closewin = setInterval(function() {
		
	 if(showwin == "close") {
	     clearInterval(closewin);
	     let displays= electron.screen.getAllDisplays();
		 //关闭旧的显示窗口
		 for(var i = 0;i < displays.length;i++)
		 {
			tempwindow[i].close();
			tempwindow[i]=null;
		 }
		 //打开新的窗口
		 startProgram();
		}
	 }, 100);

//3加载主程序
function startProgram(){
	createWindow();
	 fs.readFile("C://ip.txt", 'utf-8', (err, dataaa) => {
	     if (err) {
			 throw new Error("请在C盘的跟目录下新建一个ip.txt文档，填写上虚拟船电脑的ip地址。(C://ip.txt)");
		 }
	  iptxt=dataaa;
});
 udpclient();
 udpserver();
}
var textIntreval = setInterval(function() {
		
		//发送中英文指令
		if(showText!=textFlage){
			showalldata(showText,"text");
			textFlage=showText;
		}
		


	 }, 500);


function screenSort()
{
	let displays= electron.screen.getAllDisplays();
	
		 //需要改一下 每一个子线程更新自己的数据；
	 	   for(var i = 0;i < displays.length-1;i++) 
	 	   {
				for(var j = 0;j < displays.length-i-1;j++)
	 			 {
	 			// 	//>把大的数字放到后面       < 把小的数字放在后面
	              if(displays[j].bounds.x > displays[j+1].bounds.x)
	 			 	{
	                 var str = displays[j];
	                 displays[j] = displays[j+1];
	                 displays[j+1] = str;
					}
	          }
	      }
		 return displays;
}


function dealdata(message){
	
	var data=message.send_data_udp;
	 switch(data.id){
		case "1": messageAll.D = data.D;showText=data.showText;break;
		case "2": messageAll.LC = data.LC; messageAll.RC = data.RC;break;
		case "3": messageAll.AC = data.AC; messageAll.SS = data.SS; break;
		case "4": break; //罗经
		case "5": messageAll.DL = data.DL; messageAll.ES = data.ES;break;
		case "6": messageAll.TUG = data.TUG; break;
		case "7": messageAll.LINE = data.LINE; break;
		case "8": messageAll.CT = data.CT; break;
		case "9999": showwin=data.status; break;
		 		 
	 }

}

function showalldata(str,str1){
	
	if(str1=="data"){
		// 主进程向渲染进程触发事件 四处分发数据
		if(showindexornot==true){
				 sendWindowMessage(tempwindow[0], 'message-from-main', str)
		}
		sendWindowMessage(tempwindow[1], 'message-from-main', str) 
		sendWindowMessage(tempwindow[2], 'message-from-main', str)
		sendWindowMessage(tempwindow[3], 'message-from-main', str)
		sendWindowMessage(tempwindow[4], 'message-from-main', str)
		sendWindowMessage(tempwindow[5], 'message-from-main', str)
		sendWindowMessage(tempwindow[6], 'message-from-main', str)
		sendWindowMessage(tempwindow[7], 'message-from-main', str) 
		sendWindowMessage(tempwindow[8], 'message-from-main', str) 
				//strmsg = "";
	}
	else{
		// 主进程向渲染进程触发事件 四处分发数据
		if(showindexornot==true){
				 sendWindowMessage(tempwindow[0], 'text', showText)
		}
		sendWindowMessage(tempwindow[1], 'text', showText) 
		sendWindowMessage(tempwindow[2], 'text', showText)
		sendWindowMessage(tempwindow[3], 'text', showText)
		sendWindowMessage(tempwindow[4], 'text', showText)
		sendWindowMessage(tempwindow[5], 'text', showText)
		sendWindowMessage(tempwindow[6], 'text', showText)
		sendWindowMessage(tempwindow[7], 'text', showText) 
		sendWindowMessage(tempwindow[8], 'text', showText) 
				//strmsg = "";
		
	}
	 
}